<script setup>
import { Lock, User } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { userLoginService, userRegisterService } from '@/api/user.js'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()
const formModel = ref({
  username: '1330376',
  password: '123456',
  repassword: ''
})
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const form = ref(null)
const isRegister = ref(false)
const register = async () => {
  await form.value.validate()
  const res = await userRegisterService(formModel.value)
  console.log(res.data.code)
  if (res.data.code === 1) {
    ElMessage.error(res.data.message)
    return
  }
  ElMessage.success('注册成功')
  // 切换到登录
  isRegister.value = false
}
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})
const login = async () => {
  await form.value.validate()
  const res = await userLoginService(formModel.value)
  // 这里需要判断是否登录成功
  if (res.data.code === 1) {
    // 说明登录失败
    ElMessage.error(res.data.message)
    return
  }
  userStore.setToken(res.data.token)
  ElMessage.success('登录成功')
  router.push('/')
}
</script>

<template>
  <!--el-row表示一整行，一行分成24份-->
  <el-row class="login-page">
    <!--el-col表示列，:span="12" 代表在一行中，图标占12份-->
    <el-col :span="12" class="bg"></el-col>
    <!--登录页面占6份，两边各占3份 :offset="3"表示在一行中，margin份数-->
    <el-col :offset="3" :span="6" class="form">
      <!--这里的登录和注册使用同一个组件，通过v-if进行不同的渲染-->
      <el-form
        :model="formModel"
        :rules="rules"
        v-if="isRegister"
        ref="form"
        autocomplete="off"
        size="large"
      >
        <!--表单的每一行的都是一个 el-form-item-->
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <!--prop="username"，用于配置生效的是哪个校验规则，如果配置的是username，就说明当前的el-form-item要采用rules里面配置的username这个规则-->
        <!--prop和rules是对应的-->
        <el-form-item prop="username">
          <!--:prefix-icon="User" 配置图标，前面我们已经安装的图标库。通过不同的属性可以显示不同的图标-->
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            placeholder="请输入密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock"
            placeholder="请输入再次密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="register" auto-insert-space class="button" type="primary">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <!-- <el-link>：Element UI库中的一个组件，用于创建链接。
          type="info"：设置链接的类型为"info"，这通常对应于一种颜色主题。
          :underline="false"：使用Vue的属性绑定语法，设置链接不显示下划线。
          @click="isRegister = false"：当用户点击链接时，触发一个点击事件，将isRegister变量的值设置为false。
          ← 返回：链接的文本内容。-->
          <el-link :underline="false" type="info" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!--登录页面-->
      <el-form
        v-else
        :rules="rules"
        :model="formModel"
        ref="form"
        autocomplete="off"
        size="large"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formModel.password" :prefix-icon="Lock" name="password" placeholder="请输入密码"
                    type="password"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link :underline="false" type="primary">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="login" auto-insert-space class="button" type="primary"
          >登录
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link :underline="false" type="info" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
    url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>